package com.ycc.biz.controller;

import com.ycc.biz.exception.BusinessException;
import com.ycc.biz.pojo.entity.BizAttachment;
import com.ycc.biz.service.BizAttachmentService;
import com.ycc.biz.service.BizBuyerService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.MalformedURLException;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 文件下载控制器
 */
@Api("文件下载")
@RestController
@RequestMapping("/file")
@AllArgsConstructor
public class FileController {

    private final BizAttachmentService bizAttachmentService;
    private final String UPLOAD_DIR = "uploads/file/";

    @ApiOperation("下载文件")
    @GetMapping("/download/{id:.+}")
    public ResponseEntity<Resource> downloadFile(@ApiParam("文件名") @PathVariable String id) {
        try {
            BizAttachment attachment = bizAttachmentService.getById(id);
            String filename = attachment.getFilename();
            // 构建文件路径
            Path filePath = Paths.get(UPLOAD_DIR).resolve(filename).normalize();
            Resource resource = new UrlResource(filePath.toUri());

            // 检查文件是否存在
            if (!resource.exists()) {
                throw new BusinessException(404, "文件不存在");
            }

            // 获取文件类型
            String contentType = "application/octet-stream";
            if (filename.toLowerCase().endsWith(".jpg") || filename.toLowerCase().endsWith(".jpeg")) {
                contentType = "image/jpeg";
            } else if (filename.toLowerCase().endsWith(".png")) {
                contentType = "image/png";
            } else if (filename.toLowerCase().endsWith(".gif")) {
                contentType = "image/gif";
            }

            // 返回文件
            return ResponseEntity.ok()
                    .contentType(MediaType.parseMediaType(contentType))
                    .header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + filename + "\"")
                    .body(resource);
        } catch (MalformedURLException e) {
            throw new BusinessException(500, "文件路径错误");
        }
    }
} 